package com.hotec.PROJECT_NAME.utils;

import com.hotec.PROJECT_NAME.component.basic.ConstantKey;
import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import com.hotec.PROJECT_NAME.modules.sys.entity.SysAccount;
import com.hotec.PROJECT_NAME.modules.sys.service.SysAccountService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 账户相关属性验证工具
 *
 * @author
 */
public class UtilsAccount {
    public static String getCurrentAccountId(Boolean... strict) {
//        if(1==1){
//            return "958cfcb72c014602a7c81408c5311202";
//        }

        boolean isStrict = false;
        if (strict.length == 0) {
            isStrict = true;
        } else if (strict[0]) {
            isStrict = true;
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || ConstantKey.ANON_USER.equals(authentication.getPrincipal())) {
            if (isStrict) {
                throw new BizException(401, "请先登录再进行操作!");
            } else {
                return null;
            }
        }
        return authentication.getPrincipal().toString();
    }

    public static SysAccount getCurrentAccount(Boolean... strict) {
        SysAccount sysAccount = UtilsSpring.getBean(SysAccountService.class).get(UtilsAccount.getCurrentAccountId(strict));
        return sysAccount;
    }
    public static List<String> getCurrentAccountRoles(Boolean... strict) {

        boolean isStrict = false;
        if (strict.length == 0) {
            isStrict = true;
        } else if (strict[0]) {
            isStrict = true;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || ConstantKey.ANON_USER.equals(authentication.getPrincipal())) {
            if (isStrict) {
                throw new BizException(401, "请先登录再进行操作!");
            } else {
                return null;
            }
        }
        return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
    }
}
